package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/ethclient"
)

var connect_cli *ethclient.Client

const keyin = `{"address":"f08db7576803c00aa197b5ca237ef0c62c4e93e6","crypto":{"cipher":"aes-128-ctr","ciphertext":"133137ecee40b8c3417dd011df1ff28f1ea45ec56f051f1a63a9a213a818e013","cipherparams":{"iv":"2d2be6bb86fe4a290ebcdd820f094434"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"b4a2472ceb98fb126931e3fa5e8ddfefad73ff6f6468f0bde2027f9b8e59b859"},"mac":"9b7cd1f75cacaaa7a16a296cdad664c20e35bf6fd81f9169781959fc2b6692e4"},"id":"ec81a896-42e9-4d44-b4f5-a368d84bf05c","version":3}`
const contract_address = ``

func init() {

	client, err := ethclient.Dial("http://localhost:8545")
	if err != nil {
		log.Panic("failed to Dial ", err)
	}

	connect_cli = client

}

func help() {
	fmt.Println("./hello 1 newmsg -- for deploy contract")
	fmt.Println("./hello 2 addr -- for call getMsg")
	fmt.Println("./hello 3 addr newmsg -- for call setMsg")
}

func main() {
	if len(os.Args) < 2 {
		help()
		os.Exit(1)
	}
	if os.Args[1] == "1" {
		DeplyContract(os.Args[2])
	} else if os.Args[1] == "2" {
		callGetMsg(os.Args[2])
	} else if os.Args[1] == "3" {
		callSetMsg(os.Args[2], os.Args[3])
	}

}

func DeplyContract(dmsg string) {

	chainid, _ := connect_cli.ChainID(context.Background())
	auth, err := bind.NewTransactorWithChainID(strings.NewReader(keyin), "123", chainid)
	if err != nil {
		log.Panic("Failed to NewTransactor ", err)
	}

	addr, _, _, err := DeployHello(auth, connect_cli, dmsg)
	if err != nil {
		log.Fatal("faile to DeployHello ", err)
	}

	fmt.Printf("depoly contract sucess, address is%v\n", addr.Hex())

}

func callGetMsg(addr string) {
	instance, err := NewHello(common.HexToAddress(addr), connect_cli)
	if err != nil {
		log.Fatal("Failed to NewHello ", err)
	}
	strmsg, err := instance.GetMsg(nil)
	if err != nil {
		log.Fatal("Failed to GetMsg ", err)
	}
	fmt.Println("getmsg:", strmsg)
}

func callSetMsg(addr, newmsg string) {
	instance, err := NewHello(common.HexToAddress(addr), connect_cli)
	if err != nil {
		log.Fatal("Failed to NewHello ", err)
	}

	chainid, _ := connect_cli.ChainID(context.Background())
	auth, err := bind.NewTransactorWithChainID(strings.NewReader(keyin), "123", chainid)
	if err != nil {
		log.Panic("Failed to NewTransactor ", err)
	}

	_, err = instance.SetMsg(auth, newmsg)
	if err != nil {
		log.Fatal("Failed to SetMsg ", err)
	}
	fmt.Println("callSetMsg done")
}
